// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.standard.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.liuxinlong.common.AosException;
import com.liuxinlong.common.ExcelData;
import com.liuxinlong.common.ExcelImportCallBack;
import com.liuxinlong.common.ExcelImportService;
import com.liuxinlong.common.ImportResp;
import com.liuxinlong.common.RowError;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.SystemConstants;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.enums.DesignStatusEnum;
import com.liuxinlong.enums.FileBusinessTypeEnum;
import com.liuxinlong.enums.MandatoryEnum;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.enums.SecurityLevelEnum;
import com.liuxinlong.modules.dao.BackupDao;
import com.liuxinlong.modules.dao.ClassificationDao;
import com.liuxinlong.modules.dao.DataPushDao;
import com.liuxinlong.modules.dao.DepartmentDao;
import com.liuxinlong.modules.dao.DesignStandardDraftDao;
import com.liuxinlong.modules.dao.FileManageDao;
import com.liuxinlong.modules.dao.FileTemporaryDao;
import com.liuxinlong.modules.dao.HierarchyDao;
import com.liuxinlong.modules.dao.ParameterDao;
import com.liuxinlong.modules.dao.StandardContentDao;
import com.liuxinlong.modules.dao.StandardDao;
import com.liuxinlong.modules.dao.UserDao;
import com.liuxinlong.modules.dao.UserGroupDao;
import com.liuxinlong.modules.dao.UserGroupRelationDao;
import com.liuxinlong.modules.dao.UserRoleRelationDao;
import com.liuxinlong.modules.dao.UserStandardPermissionDao;
import com.liuxinlong.modules.entity.Backup;
import com.liuxinlong.modules.entity.DataPushRecord;
import com.liuxinlong.modules.entity.DesignStandardDraft;
import com.liuxinlong.modules.entity.FileManage;
import com.liuxinlong.modules.entity.FileTemporary;
import com.liuxinlong.modules.entity.Standard;
import com.liuxinlong.modules.entity.StandardContent;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.entity.UserGroup;
import com.liuxinlong.modules.entity.UserGroupRelation;
import com.liuxinlong.modules.entity.UserStandardPermission;
import com.liuxinlong.modules.standard.service.StandardService;
import com.liuxinlong.modules.system.dto.BackupDto;
import com.liuxinlong.modules.system.service.FileManageService;
import com.liuxinlong.utils.ExcelUtils;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 标准服务层实现类
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2022年2月7日
 */
@Slf4j
@Service
public class StandardServiceImpl implements StandardService {

    @Autowired
    private StandardDao standardDao;

    @Autowired
    private HierarchyDao hierarchyDao;

    @Autowired
    private ParameterDao parameterDao;

    @Autowired
    private ClassificationDao classificationDao;

    @Autowired
    private ExcelImportService excelImportService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private DesignStandardDraftDao designStandardDraftDao;

    @Autowired
    private BackupDao backupDao;

    @Autowired
    private FileManageDao fileManageDao;

    @Autowired
    private StandardContentDao standardContentDao;

    @Autowired
    private UserGroupDao userGroupDao;

    @Autowired
    private FileManageService fileManageService;

    @Autowired
    private UserStandardPermissionDao userStandardPermissionDao;

    @Autowired
    private UserGroupRelationDao userGroupRelationDao;

    @Autowired
    private DataPushDao dataPushDao;

    @Autowired
    private UserRoleRelationDao userRoleRelationDao;

    @Autowired
    private FileTemporaryDao fileTemporaryDao;

    @Override
    public List<Map<String, Object>> pageStandardInfo(Map<String, Object> queryParam) {
        int startNum = (int) queryParam.get("startNum");
        List<Standard> originList = standardDao.pageStandardList(queryParam);
        return completeResult(originList, startNum);
    }

    @Override
    public int getStandardCount(Map<String, Object> queryParam) {
        return standardDao.getStandardCount(queryParam);
    }

    @Transactional
    @Override
    public void addStandardInfo(Standard standard, String content) {
        String currentSn = standard.getStandardSn().substring(6);
        String id = SnowFlake.nextIdStr();
        standard.setId(id);
        updateMainFile(standard, null);
        updateMainPdfFile(standard, null);
//        String attach;
//        if (StringUtils.isNotEmpty(standard.getAttach()) && StringUtils.isNotEmpty(standard.getMasterFile())) {
//            attach = standard.getAttach() + "," + standard.getMasterFile();
//        } else {
//            attach = StringUtils.isNotEmpty(standard.getAttach()) ? standard.getAttach() : standard.getMasterFile();
//        }
//        if (StringUtils.isNotEmpty(attach)) {
//            fileManageService.updateBusinessFile(attach, id);
//        }
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        standard.setCreateUser(currentUser.getId());
        standard.setDepartment(currentUser.getDepartment());
        standardDao.insert(standard);
        parameterDao.updateParameterValue(SystemConstants.GENERATE_CODE_PARAM, currentSn);
        if (StringUtils.isNotEmpty(content)) {
            StandardContent sc = new StandardContent();
            sc.setId(SnowFlake.nextIdStr());
            sc.setStandardId(id);
            sc.setContent(content);
            standardContentDao.insert(sc);
        }
    }

    @Override
    @Transactional
    public void updateStandardInfo(Standard standard, String content) {
        String id = standard.getId();
        if (StringUtils.isEmpty(id)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "参数异常，id不存在");
        }
        Standard oldInfo = standardDao.selectById(id);
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "参数异常，原设计标准不存在");
        }
//        String attach;
//        if (StringUtils.isNotEmpty(standard.getAttach()) && StringUtils.isNotEmpty(standard.getMasterFile())) {
//            attach = standard.getAttach() + "," + standard.getMasterFile();
//        } else {
//            attach = StringUtils.isNotEmpty(standard.getAttach()) ? standard.getAttach() : standard.getMasterFile();
//        }
//        fileManageService.updateBusinessFile(attach, id);
        updateMainFile(standard, oldInfo);
        updateMainPdfFile(standard, oldInfo);
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        // 未发布时，用户可直接修改文件
        if (StringUtils.isEmpty(oldInfo.getPublishTime())) {
            standard.setUpdateUser(currentUser.getAccount());
            standardDao.updateById(standard);
            if (StringUtils.isNotEmpty(content)) {
                StandardContent oldSc = standardContentDao.getStandardContent(id);
                if (!ObjectUtils.isEmpty(oldSc)) {
                    oldSc.setContent(content);
                    standardContentDao.updateById(oldSc);
                    return;
                }
                StandardContent sc = new StandardContent();
                sc.setId(SnowFlake.nextIdStr());
                sc.setStandardId(id);
                sc.setContent(content);
                standardContentDao.insert(sc);
            }
            return;
        }
        oldInfo.setUpdateUser(currentUser.getAccount());
        oldInfo.setEdition(oldInfo.getEdition() + 1);
        standardDao.updateById(oldInfo);

        // 数据暂存草稿信息表
        DesignStandardDraft draft = new DesignStandardDraft();
        draft.setStandardId(id);
        draft.setName(standard.getName());
        draft.setStatus(standard.getStatus());
        draft.setApplicability(standard.getApplicability());
        draft.setOperateUser(standard.getOperateUser());
        draft.setMandatory(standard.getMandatory());
        draft.setStandardSn(standard.getStandardSn());
        draft.setVersion(standard.getVersion());
        draft.setReviewDepartment(standard.getReviewDepartment());
        draft.setClassification(standard.getClassification());
        draft.setHierarchy(standard.getHierarchy());
        draft.setSecurityLevel(standard.getSecurityLevel());
        draft.setAttach(standard.getAttach());
        draft.setRemark(standard.getRemark());
        draft.setTrialEndTime(standard.getTrialEndTime());
        draft.setTrialStartTime(standard.getTrialStartTime());
        draft.setReviewTime(standard.getReviewTime());
        draft.setMasterFile(standard.getMasterFile());

        draft.setDepartment(oldInfo.getDepartment());
        draft.setCreateUser(oldInfo.getCreateUser());
        draft.setUpdateUser(currentUser.getId());
        draft.setCreateTime(oldInfo.getCreateTime());
        DesignStandardDraft oldDraft = designStandardDraftDao.getDraftByStandard(id);
        if (ObjectUtils.isEmpty(oldDraft)) {
            draft.setId(SnowFlake.nextIdStr());
            designStandardDraftDao.insert(draft);
        } else {
            draft.setId(oldDraft.getId());
            designStandardDraftDao.updateById(draft);
        }
        if (StringUtils.isNotEmpty(content)) {
            StandardContent oldSc = standardContentDao.getStandardContent(id);
            if (!ObjectUtils.isEmpty(oldSc)) {
                oldSc.setContent(content);
                standardContentDao.updateById(oldSc);
                return;
            }
            StandardContent sc = new StandardContent();
            sc.setId(SnowFlake.nextIdStr());
            sc.setStandardId(id);
            sc.setContent(content);
            standardContentDao.insert(sc);
        }
    }

    @Override
    @Transactional
    public void deleteStandardInfo(String id) {
        Standard standard = standardDao.selectById(id);
        if (ObjectUtils.isEmpty(standard)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "删除失败，标准不存在!");
        }
        standardDao.deleteById(id);
        List<UserGroup> groupList = userGroupDao.queryUserGroupList();
        List<UserGroup> backList = groupList.stream().filter(item -> StringUtils.equals(item.getName(), "History Doc")).collect(Collectors.toList());
        String backFilePath = backList.get(0).getId();
        String oldMainFile = standard.getMasterFile();
        if (StringUtils.isNotEmpty(oldMainFile)) {
            fileManageService.moveFile(oldMainFile, 1, backFilePath);
        }
    }

    /**
     * 补全数据
     *
     * @param originList 原始数据
     * @param startNum   起始数
     * @return 补全数据列表
     */
    private List<Map<String, Object>> completeResult(List<Standard> originList, int startNum) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (ObjectUtil.isEmpty(originList)) {
            return resultList;
        }
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        Map<String, Map<String, String>> hierarchyMap = hierarchyDao.getHierarchyMap();
        Map<String, Map<String, String>> classificationMap = classificationDao.getClassificationMap();
        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        Map<String, Map<String, String>> draftMap = designStandardDraftDao.getDraftMap();
        int sort = startNum + 1;
        for (Standard item : originList) {
            Map<String, Object> map = ObjectUtils.object2Map(item);
            map.put("sort", sort);
            String hierarchyId = item.getHierarchy();
            if (StringUtils.isNotEmpty(hierarchyId)) {
                Map<String, String> hierarchyInfo = hierarchyMap.get(hierarchyId);
                if (!ObjectUtils.isEmpty(hierarchyInfo)) {
                    map.put("hierarchyName", hierarchyInfo.get("name"));
                }
            }
            Map<String, String> classificationInfo = classificationMap.get(item.getClassification());
            if (!ObjectUtils.isEmpty(classificationInfo)) {
                map.put("classificationName", classificationInfo.get("name"));
            }
            map.put("statusName", DesignStatusEnum.getNameByValue(item.getStatus()));
            map.put("mandatoryName", MandatoryEnum.getNameByValue(item.getMandatory()));
            map.put("securityLevelName", SecurityLevelEnum.getNameByValue(item.getSecurityLevel()));
            String operateUser = item.getOperateUser();
            if (StringUtils.isEmpty(operateUser)) {
                map.put("operable", 1);
            } else {
                map.put("operable", StringUtils.equals(currentUser.getId(), operateUser) ? 1 : 2);
                Map<String, String> user = userMap.get(operateUser);
                if (!ObjectUtils.isEmpty(user)) {
                    map.put("operateUserName", user.get("name"));
                }
            }
            if (draftMap.containsKey(item.getId())) {
                map.put("draft", 1);
            }
            map.put("mainInfo", StringUtils.isNotEmpty(item.getMasterFile()));
            map.put("attachInfo", StringUtils.isNotEmpty(item.getAttach()) ? item.getAttach().split(",").length : 0);
            resultList.add(map);
            sort++;
        }
        return resultList;
    }

    @Override
    public void exportStandardInfo(String id, HttpServletResponse response) {
        Map<String, Map<String, String>> hierarchyMap = hierarchyDao.getHierarchyMap();
        Map<String, Map<String, String>> departmentMap = departmentDao.getDepartmentMap();
        Map<String, Map<String, String>> classificationMap = classificationDao.getClassificationMap();
        Map<String, Map<String, String>> groupMap = userGroupDao.getGroupMap();
        Map<String, Map<String, String>> fileMap = fileManageDao.getFileMap(FileBusinessTypeEnum.DESIGN_STANDARD_MASTER.getValue());
        Map<String, Map<String, String>> filePdfMap = fileManageDao.getFileMap(FileBusinessTypeEnum.DESIGN_STANDARD_MASTER_PDF.getValue());

        ExcelData data = new ExcelData();
        data.setFileName("标准导出excel.xlsx");
        List<Standard> standardList = standardDao.getStandardList();
        String[] head = {"标准编号", "标准名称", "标准类型", "作用层级", "部门", "回顾部门", "标准分类", "子分类", "曾用名", "强制分类", "版本",
                "保密等级", "适用范围", "参考标准", "状态", "发布时间", "用户组", "主文件", "主文件PDF", "备注"};
        data.setHead(head);
        String[][] dataList = new String[standardList.size()][head.length];
        int index = 0;
        for (Standard ds : standardList) {
            dataList[index][0] = ds.getStandardSn();
            dataList[index][1] = ds.getName();
            dataList[index][2] = ds.getStandardType() == 1 ? "设计标准" : ds.getStandardType() == 2 ? "测试标准" : "设计&测试标准";
            dataList[index][3] = StringUtils.isNotEmpty(ds.getHierarchy()) ?
                    hierarchyMap.containsKey(ds.getHierarchy()) ? hierarchyMap.get(ds.getHierarchy()).get("name") : "" : "";
            dataList[index][4] = StringUtils.isNotEmpty(ds.getDepartment()) ?
                    departmentMap.containsKey(ds.getDepartment()) ? departmentMap.get(ds.getDepartment()).get("name") : "" : "";
            dataList[index][5] = ds.getReviewDepartment();
//            dataList[index][5] = StringUtils.isNotEmpty(ds.getReviewDepartment()) ?
//                    departmentMap.containsKey(ds.getReviewDepartment()) ? departmentMap.get(ds.getReviewDepartment()).get("name") : "" : "";
            dataList[index][6] = StringUtils.isNotEmpty(ds.getClassification()) ?
                    classificationMap.containsKey(ds.getClassification()) ? classificationMap.get(ds.getClassification()).get("name") : "" : "";
            dataList[index][7] = StringUtils.isNotEmpty(ds.getSubClassification()) ?
                    classificationMap.containsKey(ds.getSubClassification()) ? classificationMap.get(ds.getSubClassification()).get("name") : "" : "";
            dataList[index][8] = ds.getOldName();
            dataList[index][9] = ds.getMandatory() == 1 ? "强制" : ds.getMandatory() == 2 ? "推荐" : "试行";
            dataList[index][10] = ds.getVersion();
            dataList[index][11] = ds.getSecurityLevel() == 1 ? "A" : "B";
            dataList[index][12] = ds.getApplicability();
            dataList[index][13] = ds.getReference();
            dataList[index][14] = DesignStatusEnum.getNameByValue(ds.getStatus());
            dataList[index][15] = ds.getPublishTime();
            dataList[index][16] = groupMap.containsKey(ds.getGroupId()) ? groupMap.get(ds.getGroupId()).get("name") : "";
            dataList[index][17] = StringUtils.isNotEmpty(ds.getMasterFile()) ?
                    fileMap.containsKey(ds.getMasterFile()) ? fileMap.get(ds.getMasterFile()).get("name") : "" : "";
            dataList[index][18] = StringUtils.isNotEmpty(ds.getMasterPdfFile()) ?
                    filePdfMap.containsKey(ds.getMasterPdfFile()) ? filePdfMap.get(ds.getMasterPdfFile()).get("name") : "" : "";

            dataList[index][19] = ds.getRemark();

            index++;
        }
        data.setData(Arrays.asList(dataList));
        ExcelUtils.exportExcel(response, data);
    }

    @Override
    public ImportResp batchAddStandard(List<Standard> dataList) {
        Map<String, Map<String, String>> standardSnMap = standardDao.getStandardSnMap();
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        List<Map> failedList = new ArrayList<>();
        boolean insertSuccess;
        int sort = 1;
        for (Standard standard : dataList) {
            String message = "";
            if (standardSnMap.size() > 0 && standardSnMap.containsKey(standard.getStandardSn())) {
                message = "标准编号已存在";
                insertSuccess = false;
            } else {
                String id = SnowFlake.nextIdStr();
                standard.setId(id);
                standard.setDepartment(currentUser.getDepartment());
                standard.setCreateUser(currentUser.getId());
                try {
                    standardDao.insert(standard);
                    insertSuccess = true;
                } catch (Exception e) {
                    insertSuccess = false;
                    message = e.getMessage();
                }
            }
            if (!insertSuccess) {
                Map<String, Object> map = ObjectUtils.object2Map(standard);
                map.put("sort", sort);
                map.put("message", message);
                sort++;
                failedList.add(map);
            }
        }
        ImportResp resp = new ImportResp();
        resp.setRetCode(failedList.size() > 0 ? ReturnCodes.HTTP_IMPORT_PART_FAIL.getRetCode() : ReturnCodes.HTTP_SUCCESS.getRetCode());
        resp.setFailedList(failedList);
        resp.setRetMessage(failedList.size() > 0 ? "导入设计标准信息部分成功" : "导入设计标准信息成功");
        return resp;
    }

    @Override
    public void lockDesignStandard(String id) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        Standard standard = standardDao.selectById(id);
        if (ObjectUtils.isEmpty(standard)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "参数异常，设计标准不存在！");
        }
        if (standard.getStatus() != DesignStatusEnum.PREPARATION.getValue() &&
                standard.getStatus() != DesignStatusEnum.PUBLISHED.getValue()) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "参数异常，设计标准状态异常！");
        }
        String operateUser = standard.getOperateUser();
        String currentUserId = currentUser.getId();
        if (StringUtils.isNotEmpty(operateUser) &&
                !StringUtils.equals(operateUser, currentUserId)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "参数异常，设计标准已被锁定！");
        }
        standard.setOperateUser(currentUser.getId());
        standardDao.updateById(standard);
    }

    @Override
    public void processStandard(String id) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        Standard standard = standardDao.selectById(id);
        if (ObjectUtils.isEmpty(standard)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "参数异常，设计标准不存在！");
        }
        if (standard.getStatus() != DesignStatusEnum.PREPARATION.getValue()) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "参数异常，设计标准非编制中！");
        }
        String operateUser = standard.getOperateUser();
        String currentUserId = currentUser.getId();
        if (StringUtils.isNotEmpty(standard.getOperateUser()) &&
                !StringUtils.equals(operateUser, currentUserId)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "参数异常，设计标准被其他用户锁定！");
        }
//        standard.setOperateUser(currentUserId);
//        standard.setStatus(DesignStatusEnum.REVIEW.getValue());
        standard.setStatus(DesignStatusEnum.PUBLISHED.getValue());
        standard.setOperateUser(null);
        standardDao.updateById(standard);
    }

    @Override
    public void unlockDesignStandard(String id) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        Standard standard = standardDao.selectById(id);
        if (ObjectUtils.isEmpty(standard)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "参数异常，设计标准不存在！");
        }
        if (standard.getStatus() != DesignStatusEnum.PREPARATION.getValue()) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "参数异常，设计标准状态异常！");
        }
        String operateUser = standard.getOperateUser();
        String currentUserId = currentUser.getId();
        if (StringUtils.isEmpty(operateUser)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "参数异常，设计标准未被锁定！");
        }
        if (!StringUtils.equals(operateUser, currentUserId)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "参数异常，非法解锁！");
        }
        standard.setOperateUser("");
        standardDao.updateById(standard);
    }

    @Override
    public Map<String, Object> loadDraft(String id) {
        DesignStandardDraft draftOrigin = designStandardDraftDao.getDraftByStandard(id);
        draftOrigin.setId(draftOrigin.getStandardId());
        return ObjectUtils.object2Map(draftOrigin);
    }

    @Override
    public List<Map<String, Object>> queryStandardVersion(String standardId) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<BackupDto> originList = backupDao.getBackupList(standardId);
        if (originList.size() == 0) {
            return resultList;
        }
        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        int sort = 1;
        for (BackupDto item : originList) {
            Map<String, Object> map = ObjectUtils.object2Map(item);
            map.put("sort", sort);
            Map<String, String> userInfo = userMap.get(item.getOperateUser());
            map.put("userName", userInfo.get("name"));
            sort++;
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public List<Map<String, Object>> queryStandardFile(String standardId) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<FileManage> originList = fileManageDao.queryFileManageList(standardId);
        if (originList.size() == 0) {
            return resultList;
        }
        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        int sort = 1;
        for (FileManage item : originList) {
            Map<String, Object> map = ObjectUtils.object2Map(item);
            map.put("sort", sort);
            map.put("operateUserName", userMap.containsKey(item.getOperateUser()) ? userMap.get(item.getOperateUser()).get("name") : "");
            sort++;
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public void abolishStandard(String id) {
        Standard standard = standardDao.selectById(id);
        if (ObjectUtils.isEmpty(standard)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "参数异常，设计标准不存在！");
        }
        standard.setStatus(DesignStatusEnum.REPEALED.getValue());
        standardDao.updateById(standard);
        List<UserGroup> groupList = userGroupDao.queryUserGroupList();
        List<UserGroup> backList = groupList.stream().filter(item -> StringUtils.equals(item.getName(), "History Doc")).collect(Collectors.toList());
        String backFilePath = backList.get(0).getId();
        String oldMainFile = standard.getMasterFile();
        if (StringUtils.isNotEmpty(oldMainFile)) {
            fileManageService.moveFile(oldMainFile, 1, backFilePath);
        }
    }

    @Override
    public void getStandardFile(String fileId, String userSn, HttpServletResponse response) {
        if (StringUtils.isEmpty(fileId)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件不存在！");
        }
        if (StringUtils.isEmpty(userSn)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "用户不存在！");
        }
        FileManage fileManage = fileManageDao.selectById(fileId);
        if (ObjectUtils.isEmpty(fileManage)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件不存在！");
        }
        Standard standard = standardDao.selectById(fileManage.getBusinessId());
        if (ObjectUtils.isEmpty(standard)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件不存在！");
        }
        User user = userDao.getUserBySn(userSn);
        if (ObjectUtils.isEmpty(user)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "用户不存在！");
        }
        UserStandardPermission usp = userStandardPermissionDao.getUserStandard(user.getId(), standard.getId());
        if (ObjectUtils.isEmpty(usp)) {
            UserGroupRelation relation = userGroupRelationDao.queryRelationByInfo(user.getId(), standard.getGroupId());
            if (ObjectUtils.isEmpty(relation)) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "用户不具备该文件查看权限！");
            }
        }
//        FileManage fileManage = fileManageDao.selectById(standard.getMasterPdfFile());
//        if (ObjectUtils.isEmpty(fileManage)) {
//            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件不存在！");
//        }

        String filePath = fileManage.getFilePath();
        try {
            File inputFile = new File(filePath);
            InputStream fileInputStream = new FileInputStream(inputFile);

            response.setHeader("Content-Disposition", "attachment;fileName=" + fileManage.getName());
            response.setContentType("multipart/form-data");
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
            //关流
            outputStream.close();
//            inputStream.close();
        } catch (Exception e) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "转换文件失败");
        }
    }

    @Override
    public ImportResp importStandards(String fileName) {
        String filePath = fileName;
        return excelImportService.excelFile(filePath, 2, new ExcelImportCallBack() {
            @Override
            public Collection<RowError> checkRow(String[] record) {
                return checkRecordValid(record);
            }

            @Override
            public boolean persistRowToDb(String[] record) {
                Standard standard = covertToBean(record);
                return false;
//				try {
//					materialStandardDao.insert(mocDetail);
//					return true;
//				} catch (Exception e) {
//					return false;
//				}
            }

            @Override
            public ImportResp partFailure(ImportResp resp) {
                resp.setRetCode(ReturnCodes.HTTP_SUCCESS.getRetCode());
                resp.setRetMessage("导入物料替换数据部分失败，总数=" + resp.getTotal() + ",失败总数=" + resp.getFailedTotal());
                return resp;
            }

            @Override
            public ImportResp allSuccess(ImportResp resp) {
                resp.setRetMessage("导入物料替换数据全部成功，总数=" + resp.getTotal());
                return resp;
            }

            @Override
            public List<Map> convertFailList(List<String[]> failRecords) {
                List<Map> list = new ArrayList<>();
                int sort = 1;
                for (String[] failRecord : failRecords) {
                    if (StringUtils.isEmpty(failRecord[3]) || StringUtils.equals(failRecord[3].trim(), "其他") || StringUtils.isEmpty(failRecord[9])) {
                        continue;
                    }
                    Map item = new HashMap();
                    item.put("sort", sort);
                    item.put("standardSn", failRecord[1]);
                    item.put("name", failRecord[2]);
                    item.put("standardType", StringUtils.equals(failRecord[3].trim(), "设计标准") ? 1 : StringUtils.equals(failRecord[3].trim(), "测试标准") ? 2 : 3);
                    item.put("reviewDepartment", StringUtils.isNotEmpty(failRecord[4]) ? failRecord[4].trim() : "");
                    item.put("hierarchy", failRecord[5]);
                    item.put("classification", failRecord[6]);
                    item.put("mandatory", StringUtils.equals(failRecord[7].trim(), "强制") ? 1 : StringUtils.equals(failRecord[7].trim(), "推荐") ? 2 : 3);
                    item.put("version", failRecord[8]);
                    item.put("securityLevel", StringUtils.equals(failRecord[9].trim(), "A") ? 1 : 2);
                    item.put("applicability", failRecord[10]);
                    list.add(item);
                    sort++;
                }
                return list;
            }

        });
    }

    /**
     * 转换数据为入库数据
     *
     * @param record 数据记录
     * @return 入库数据
     */
    private Standard covertToBean(String[] record) {
        Standard standard = new Standard();
        standard.setStandardSn(record[1].trim());
        standard.setName(record[2].trim());
        standard.setReviewDepartment(record[4].trim());
        standard.setHierarchy(record[5].trim());
        standard.setClassification(record[6].trim());
        standard.setMandatory(2);
        standard.setVersion(record[8].trim());
        standard.setSecurityLevel(StringUtils.equals(record[9].trim(), "A") ? 1 : 2);
        standard.setApplicability(record[10].trim());
        return standard;

    }

    /**
     * 校验参数合法性
     *
     * @param record 导入数据
     * @return 参数合法性
     */
    private Collection<RowError> checkRecordValid(String[] record) {
        List<RowError> rowErrors = new ArrayList<>();
        if (StringUtils.isEmpty(record[1].trim())) {
            addRowError("设计编号不能为空", rowErrors);
        } else {
            if (record[1].trim().length() > 20) {
                addRowError("设计编号长度不能超过20", rowErrors);
            }
        }
        if (StringUtils.isEmpty(record[2].trim())) {
            addRowError("设计名称不能为空", rowErrors);
        } else {
            if (record[2].trim().length() > 100) {
                addRowError("设计名称长度不能超过100", rowErrors);
            }
        }
        if (StringUtils.isEmpty(record[2].trim())) {
            addRowError("兼容性不能为空", rowErrors);
        } else {

            if (record[2].trim().length() > 100) {
                addRowError("兼容性字段非法", rowErrors);
            }
        }
        if (StringUtils.isEmpty(record[4].trim())) {
            addRowError("回顾部门不能为空", rowErrors);
        } else {
            if (record[4].trim().length() > 20) {
                addRowError("回顾部门长度不能超过20", rowErrors);
            }
        }
        return rowErrors;
    }

    /**
     * 添加错误行数据
     *
     * @param errorMessage 错误信息
     * @param rowErrors    错误行数据
     */
    private void addRowError(String errorMessage, List<RowError> rowErrors) {
        RowError rowError = new RowError(errorMessage);
        rowErrors.add(rowError);
    }

    /**
     * 更新主文件信息
     *
     * @param newInfo 新标准信息
     * @param oldInfo 原标准信息
     */
    private void updateMainFile(Standard newInfo, Standard oldInfo) {
        String mainFile = newInfo.getMasterFile();
        boolean addFlag = ObjectUtils.isEmpty(oldInfo);
        if (addFlag && StringUtils.isEmpty(mainFile)) {
            return;
        }
        if (addFlag || StringUtils.isEmpty(oldInfo.getMasterFile())) {
            if (StringUtils.isEmpty(mainFile)) {
                return;
            }
            FileManage fileManage = fileManageDao.selectById(mainFile);
            fileManage.setBusinessId(newInfo.getId());
            fileManageDao.updateFileManage(fileManage);
            return;
        }
        String oldMainFile = oldInfo.getMasterFile();
        if (StringUtils.equals(mainFile, oldMainFile)) {
            return;
        }

        // 原文件备份
        FileManage oldFileManage = fileManageDao.selectById(oldMainFile);
        if (!ObjectUtils.isEmpty(oldFileManage)) {
            Backup backup = new Backup();
            backup.setId(SnowFlake.nextIdStr());
            backup.setFileId(oldMainFile);
            backup.setBusinessType(1);
            backup.setBusinessId(newInfo.getId());
            backup.setVersion(newInfo.getVersion() + "." + oldInfo.getEdition());
            backup.setStartTime(oldFileManage.getOperateTime());
            String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
            backup.setOperateTime(currentTime);
            backup.setEndTime(currentTime);
            backupDao.insert(backup);
            List<UserGroup> groupList = userGroupDao.queryUserGroupList();
            List<UserGroup> backList = groupList.stream().filter(item -> StringUtils.equals(item.getName(), "History Doc")).collect(Collectors.toList());
            if (backList.size() == 0) {
                throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "更新标准主文件失败，备份库不存在");
            }
            String backFilePath = backList.get(0).getId();
            fileManageService.moveFile(oldMainFile, 1, backFilePath);
            UserGroup userGroup = userGroupDao.selectById(newInfo.getGroupId());
            String filePath = oldFileManage.getFilePath().replace(userGroup.getFolderPath(), backList.get(0).getFolderPath());
            oldFileManage.setStatus(1);
            oldFileManage.setFilePath(filePath);
            fileManageDao.updateById(oldFileManage);
        }

        if (StringUtils.isEmpty(mainFile)) {
            return;
        }
        FileManage fileManage = fileManageDao.selectById(mainFile);
        fileManage.setBusinessId(newInfo.getId());
        fileManageDao.updateFileManage(fileManage);
    }

    /**
     * 更新主文件pdf信息
     *
     * @param newInfo 新标准信息
     * @param oldInfo 原标准信息
     */
    private void updateMainPdfFile(Standard newInfo, Standard oldInfo) {
        String mainPdfFile = newInfo.getMasterPdfFile();
        boolean addFlag = ObjectUtils.isEmpty(oldInfo);
        if (addFlag && StringUtils.isEmpty(mainPdfFile)) {
            return;
        }

        FileTemporary newTemporary = new FileTemporary();
        newTemporary.setId(mainPdfFile);
        if (addFlag || StringUtils.isEmpty(oldInfo.getMasterPdfFile())) {
            if (StringUtils.isEmpty(mainPdfFile)) {
                return;
            }
            FileManage fileManage = fileManageDao.selectById(mainPdfFile);
            fileManage.setBusinessId(newInfo.getId());
            fileManageDao.updateFileManage(fileManage);
            newTemporary.setFilePath(fileManage.getFilePath());
            DataPushRecord dataPushRecord = new DataPushRecord();
            dataPushRecord.setId(SnowFlake.nextIdStr());
            dataPushRecord.setStatus(1);
            String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
            dataPushRecord.setOperateTime(currentTime);
            dataPushRecord.setContentOne(newInfo.getId());
            dataPushRecord.setContentTwo(fileManage.getName());
            dataPushDao.insert(dataPushRecord);
            return;
        }
        String oldMainPdfFile = oldInfo.getMasterPdfFile();
        if (StringUtils.equals(mainPdfFile, oldMainPdfFile)) {
            return;
        }
        FileManage oldFileManage = fileManageDao.selectById(oldMainPdfFile);
        if (!ObjectUtils.isEmpty(oldFileManage)) {
            FileTemporary fileTemporary = fileTemporaryDao.selectById(oldMainPdfFile);
            if (!ObjectUtils.isEmpty(fileTemporary)) {
                newTemporary.setHeat(fileTemporary.getHeat());
                newTemporary.setFilePath(fileTemporary.getFilePath());
                fileTemporaryDao.insert(newTemporary);
            }
            oldFileManage.setStatus(1);
            fileManageDao.updateById(oldFileManage);
            Backup backup = new Backup();
            backup.setId(SnowFlake.nextIdStr());
            backup.setFileId(oldMainPdfFile);
            backup.setBusinessType(1);
            backup.setBusinessId(newInfo.getId());
            backup.setVersion(newInfo.getVersion());
            backup.setStartTime(oldFileManage.getOperateTime());
            String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
            backup.setOperateTime(currentTime);
            backup.setEndTime(currentTime);
            backupDao.insert(backup);
        }

        if (StringUtils.isEmpty(mainPdfFile)) {
            return;
        }
        FileManage fileManage = fileManageDao.selectById(mainPdfFile);
        fileManage.setBusinessId(newInfo.getId());
        fileManageDao.updateFileManage(fileManage);
    }

}
